<?php

namespace app\applet\controller;

use app\applet\model\SupplyNotify;
use think\Db;
use think\Exception;

class Notify
{
    /**
     * 供应链回调函数
     *
     */
    public function supply()
    {
        $model = new SupplyNotify();
        $data = file_get_contents('php://input'); //接受通知参数；
        $data = json_decode($data,true);
        $type = $data['type'];

        #商家已发货
        if($type === "order.delivery")
        {
            $data = $data['data'];
            $orderSn = $data['orderSn']; #订单编号
            $sku     = $data['sku']; #商品sku
            //商家发货
            $supplyChain= new \app\applet\model\SupplyChain();
            $rst=$supplyChain->delivery($orderSn,$sku);
            if(empty($rst)){
                echo json_encode(['code'=>-2004]);die;
            }


        }
        #商品已收货
        if($type === "order.delivered")
        {
            $data = $data['data'];
            $orderSn = $data['orderSn']; #订单编号
            $sku     = $data['sku']; #商品sku
            #走我们自己的项目业务逻辑


        }

        #交易成功
        if($type === "order.success")
        {
            $data = $data['data'];
            $orderSn = $data['orderSn']; #订单编号
            $sku     = $data['sku']; #商品sku
            #走我们自己的项目业务逻辑

            $supplyChain= new \app\applet\model\SupplyChain();
            $rst=$supplyChain->completeOrder($orderSn,$sku);
            if(empty($rst)){
                echo json_encode(['code'=>-2004]);die;
            }
        }
        #订单取消
        if($type === "order.cancel")
        {
            $data = $data['data'];
            $orderSn = $data['orderSn']; #订单编号
            $sku     = $data['sku']; #商品sku
            #走我们自己的项目业务逻辑

        }
        #售后拒绝
        if($type === "afterSale.refuse")
        {
            $data = $data['data'];
            $afterSaleId = $data['afterSaleId']; #售后服务单id
            $orderSn = $data['orderSn']; #订单编号
            $sku     = $data['sku']; #商品sku
            #走我们自己的项目业务逻辑

        }
        #售后同意
        if($type === "afterSale.agree")
        {
            $data = $data['data'];
            $afterSaleId = $data['afterSaleId']; #售后服务单id
            $orderSn = $data['orderSn']; #订单编号
            $sku     = $data['sku']; #商品sku
            #走我们自己的项目业务逻辑

        }
        #售后退款到账
        if($type === "afterSale.success")
        {
            $data = $data['data'];
            $afterSaleId = $data['afterSaleId']; #售后服务单id
            $orderSn = $data['orderSn']; #订单编号
            $sku     = $data['sku']; #商品sku
            #走我们自己的项目业务逻辑

        }

        #商品库添加商品
        if($type === "goods.storage.add")
        {
            $goods = $data['data']['goodsIds'];
            foreach ($goods as $v)
            {
                $model->goodsAdd($v);
            }
        }
        #商品修改和商品价格变更
        if($type === "goods.alter" || $type === "goods.price.alter")
        {
            $goods = $data['data']['goodsIds'];
            foreach ($goods as $v)
            {
                $model->goodsAlter($v);
            }
        }
        #移除商品库
        if($type === "goods.storage.remove")
        {
            $goods = $data['data']['goodsIds'];
            foreach ($goods as $v)
            {
                $model->goodsRemove($v);
            }
        }
        #商品上架
        if($type === "goods.on.sale")
        {
            $goods = $data['data']['goodsIds'];
            foreach ($goods as $v)
            {
                $model->goodsOnSale($v);
            }
        }
        #商品下架
        if($type === "goods.undercarriage")
        {
            $goods = $data['data']['goodsIds'];
            foreach ($goods as $v)
            {
                $model->undercarriage($v);
            }
        }


        #收到消息，并处理成功,返回code=1,停止生命周期
        echo json_encode(['code'=>1]);die;
    }


    /**
     * 小程序支付后的回调
     * 店招支付回调111
     */
    public function shopPayment()
    {
        $xml = file_get_contents('php://input'); //接受通知参数；
        $result = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        if($result)
        {
            //如果成功返回了
            $out_trade_no = $result['out_trade_no'];
            $trade_type   = $result['trade_type'];  //判断是否是jsapi支付
            $real_money = $result['total_fee'] / 100;
            if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS')
            {
                #业务逻辑
                $data = Db::name("shop_sign_order")
                    ->field("id,member_id,pay_wx,goods_id,start_time,end_time,pay_score,member_id,status")
                    ->where(['order_sn'=>$out_trade_no])
                    ->find();
                if($data['pay_wx']==$real_money&&!in_array($data['status'],[1,2])){
                    $tm=time();
                    Db::startTrans();
                    try{
                        #改变订单状态
                        Db::name("shop_sign_order")
                            ->where(['order_sn'=>$out_trade_no])
                            ->update(['status'=>1,"update_time"=>time()]);
                        #添加店招记录表
                        #更新积分余额, 后续需要添加积分扣除记录
                        $pay_score=$data['pay_score'];
                        $pay_wx=$data['pay_wx'];
                        $member_id=$data['member_id'];
                        $relation_id=$data['id'];
                        $asset_log=[];
                        //写入微信支付记录
                        if($pay_wx>0){//生成微信支付订单记录
                            $asset_log[] = ['member_id' => $member_id, 'type' => 2, 'amount' =>$pay_wx ,
                                'source_type' => 2, 'description' => "设置店招", "change_type" => 3, 'log_type_id' => 69,
                                'relation_id' => $relation_id, 'create_time' => $tm, 'update_time' => $tm];

                        }
                        if($pay_score>0){
                            //写入记录
                            $asset_log[]  = ['member_id' => $member_id, 'type' => 2, 'amount' =>$pay_score ,
                                'source_type' => 2, 'description' => "设置店招", "change_type" => 1, 'log_type_id' => 68,
                                'relation_id' => $relation_id, 'create_time' => $tm, 'update_time' => $tm];
                            //删除记录
                            $num=Db::name("member_asset_log")->where(['log_type_id'=>53,'member_id'=>$member_id,'relation_id'=>$relation_id])->delete();
                            if($num<=0){
                                throw new Exception("更新失败");
                            }
                            //扣除
                            $sql="update mm_member_asset set frozen_score=frozen_score-$pay_score,pay_frozen_score=pay_frozen_score-$pay_score where member_id=".$member_id." and frozen_score>=$pay_score and pay_frozen_score>=$pay_score ";
                            $num=Db::query($sql);
                            if($num<=0){
                                throw  new Exception("操作失败");
                            }

                        }
                        $num=Db::name("member_asset_log")->insertAll($asset_log);
                        if($num<=0){
                            throw new Exception("更新失败");
                        }

                        $goods_id = $data['goods_id'];
                        #获取店铺id
                        $store = Db::name("goods")
                            ->field("store_id,g_type")
                            ->where(['goods_id'=>$goods_id])
                            ->find();
                        $g_type = $store['g_type'];
                        $fina = Db::name("goods_shop_sign")
                            ->where(['goods_id'=>$goods_id])
                            ->count();
                        if($fina)
                        {
                            $list['start_time'] = $data['start_time'];
                            $list['end_time'] = $data['end_time'];
                            $list['is_free'] = 2;
                            $list['is_delete'] = 1;
                            $list['update_time'] = time();
                            $num=Db::name("goods_shop_sign")
                                ->where(['goods_id'=>$goods_id])
                                ->update($list);
                        }else{
                            $list['goods_id'] = $goods_id;
                            $list['g_type'] = $g_type; #商品类别
                            $list['store_id'] = $store['store_id'];
                            $list['start_time'] = $data['start_time'];
                            $list['end_time'] = $data['end_time'];
                            $list['is_free'] = 2;
                            $list['create_time'] = time();
                            $num=Db::name("goods_shop_sign")
                                ->insert($list);
                        }
                        if($num<=0){
                            throw new Exception("更新失败");
                        }

                        Db::commit();
                        echo 'SUCCESS';
                    }catch (Exception $e){
                        Db::rollback();
                        echo 'FAIL';
                    }
                }else{
                    echo 'FAIL';
                }



            } else {
                echo 'FAIL';
            }
        }
    }


    /**
     * 订单回调
     */

    public function orderPayment()
    {
        $xml = file_get_contents('php://input'); //接受通知参数；

        $result = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

       /* $result['out_trade_no']='202007524911349014';
        $result['trade_type']='';
        $result['total_fee']=1;
        $result['return_code']='SUCCESS';
        $result['result_code']='SUCCESS';*/

        if($result)
        {
                 //如果成功返回了
                $out_trade_no = $result['out_trade_no'];
                $trade_type = $result['trade_type'];  //判断是否是jsapi支付
                $real_money = $result['total_fee'] / 100;
                if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
                    $input = [];
                    $input['order_sn'] = $out_trade_no;
                    $input['wx_pay_money'] = $real_money;
                    $Notify = new \app\applet\model\Notify();
                    $ret = $Notify->order($input);
                    $ret = json_decode($ret, true);
                    if ($ret['code'] == 200) {
                        echo 'SUCCESS';
                    } else {
                        echo 'FAIL';
                    }
                }


        } else {
            echo 'FAIL';
        }
    }

    /**
     * 积分金币转账回调
     */
    public function transferPayment(){

        $xml = file_get_contents('php://input'); //接受通知参数；
        $result = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        if($result)
        {
            //如果成功返回了
            $out_trade_no = $result['out_trade_no'];
            $trade_type   = $result['trade_type'];  //判断是否是jsapi支付
            $real_money = $result['total_fee'] / 100;
            if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
                $trans_sn= $out_trade_no;
                //获取当前转换记录
                $memberTransfer=Db::name("member_transfer")->where(['trans_sn'=>$trans_sn])->find();
                if($memberTransfer['status']==1){//待转账
                    $transfer_num=$memberTransfer['transfer_num'];
                    $pay_num=$memberTransfer['pay_num'];
                    $member_id=$memberTransfer['member_id'];
                    $receive_id=$memberTransfer['receive_id'];
                    $relation_id=$memberTransfer['trans_id'];
                    $tm=time();
                    Db::startTrans();
                    try{
                        //更新状态
                        $num=Db::name("member_transfer")->where(['trans_sn'=>$trans_sn])
                            ->update(['status'=>2,'update_time'=>$tm]);
                        if($num<=0){
                            throw  new Exception("操作失败");
                        }
                        $asset_log=[];
                        //写入微信支付记录
                        $pay_wx= $memberTransfer['wx_pay_num'];
                        if($pay_wx>0){//生成微信支付订单记录
                            $asset_log[] = ['member_id' => $member_id, 'type' => 2, 'amount' =>$pay_wx ,
                                'source_type' => 2, 'description' => "会员转账", "change_type" => 3, 'log_type_id' => 70,
                                'relation_id' => $relation_id, 'create_time' => $tm, 'update_time' => $tm];

                        }
                        if($memberTransfer['type']==1){//积分
                            //写入记录
                            $asset_log[] = ['member_id' => $member_id, 'type' => 2, 'amount' =>$pay_num ,
                                'source_type' => 2, 'description' => "会员转账", "change_type" => 1, 'log_type_id' => 13,
                                'relation_id' => $relation_id, 'create_time' => $tm, 'update_time' => $tm];
                            $receive_mobile=$memberTransfer['receive_mobile'];
                            $receive_id=$memberTransfer['receive_id'];
                            $asset_log[] = ['member_id' => $receive_id, 'type' => 1, 'amount' =>$transfer_num ,
                                'source_type' => 2, 'description' => "会员转账",'transfer_mobile'=>$receive_mobile,"transfer_id"=>$receive_id, "change_type" => 1, 'log_type_id' => 2,
                                'relation_id' =>  $relation_id, 'create_time' => $tm, 'update_time' => $tm];
                            $num=Db::name("member_asset_log")->insertAll($asset_log);
                            if($num<=0){
                                throw new Exception("更新失败10");
                            }
                            //删除记录
                            $num=Db::name("member_asset_log")->where(['log_type_id'=>55,'member_id'=>$member_id,'relation_id'=>$relation_id])->delete();
                            if($num<=0){
                                throw new Exception("更新失败10");
                            }
                            //扣除
                            $sql="update mm_member_asset set frozen_score=frozen_score-$pay_num,pay_frozen_score=pay_frozen_score-$pay_num where member_id=".$member_id." and frozen_score>=$pay_num and pay_frozen_score>=$pay_num ";
                            $num=Db::query($sql);
                            if($num<=0){
                                throw  new Exception("操作失败");
                            }
                            //新增
                            $sql="update mm_member_asset set score=score+$transfer_num where member_id=$receive_id" ;
                            $num=Db::query($sql);
                            if($num<=0){
                                throw  new Exception("操作失败");
                            }
                        }elseif($memberTransfer['type']==2){//金币
                            $asset_log=[];

                            $asset_log[] = ['member_id' => $member_id, 'type' => 2, 'amount' =>$pay_num ,
                                'source_type' => 2, 'description' => "会员转账", "change_type" => 2, 'log_type_id' => 32,
                                'relation_id' => $relation_id, 'create_time' => $tm, 'update_time' => $tm];
                            $receive_mobile=$memberTransfer['receive_mobile'];
                            $receive_id=$memberTransfer['receive_id'];
                            $asset_log[] = ['member_id' => $receive_id, 'type' => 1, 'amount' =>$transfer_num ,
                                'source_type' => 2, 'description' => "会员转账",'transfer_mobile'=>$receive_mobile,"transfer_id"=>$receive_id, "change_type" => 2, 'log_type_id' => 25,
                                'relation_id' =>  $relation_id, 'create_time' => $tm, 'update_time' => $tm];
                            $num=Db::name("member_asset_log")->insertAll($asset_log);
                            if($num<=0){
                                throw new Exception("更新失败10");
                            }
                            //删除记录
                            $num=Db::name("member_asset_log")->where(['log_type_id'=>56,'member_id'=>$member_id,'relation_id'=>$relation_id])->delete();
                            if($num<=0){
                                throw new Exception("更新失败10");
                            }
                            //扣除
                            $sql="update mm_member_asset set frozen_score=frozen_score-$pay_num where member_id=".$member_id." and frozen_score>=$pay_num  ";
                            $num=Db::query($sql);
                            if($num<=0){
                                throw  new Exception("操作失败");
                            }
                            //新增
                            $sql="update mm_member_asset set coin=coin+$transfer_num where member_id=$receive_id" ;
                            $num=Db::query($sql);
                            if($num<=0){
                                throw  new Exception("操作失败");
                            }
                        }
                        Db::commit();
                        echo 'SUCCESS';
                    }catch (Exception $e){
                        Db::rollback();
                        echo 'FAIL';
                    }
                }
            }
        } else {
            echo 'FAIL';
        }
    }

    /**
     * 到店直接支付
     */
    public function shopOfflinePayment(){

        $xml = file_get_contents('php://input'); //接受通知参数；
        $result = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        if($result) {
            //如果成功返回了

            $out_trade_no = $result['out_trade_no'];
            $trade_type = $result['trade_type'];  //判断是否是jsapi支付
            $real_money = $result['total_fee'] / 100;
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                $tm=time();
               //获取直接支付信息
               $shopPay=Db::name("shop_pay")->where(['consume_sn'=>$out_trade_no])->find();
               if($real_money==$shopPay['pay_wx']&& !in_array($shopPay['status'],[1,3])){
                   Db::startTrans();
                   try{
                       $member_id=$shopPay['member_id'];
                       $store_member_id= $shopPay['store_member_id'];
                       $amount= $shopPay['amount'];
                       $rebate_rate= $shopPay['rebate_rate'];
                       $pay_score= $shopPay['pay_score'];
                       $pay_coin= $shopPay['pay_coin'];
                       $pay_wx= $shopPay['pay_wx'];
                       $asset_log=[];
                       if($pay_wx>0){//生成微信支付订单记录
                           $asset_log[] = ['member_id' => $member_id, 'type' => 2, 'amount' =>$pay_wx ,
                               'source_type' => 2, 'description' => "到店支付", "change_type" => 3, 'log_type_id' => 36,
                               'relation_id' => $shopPay['sp_id'], 'create_time' => $tm, 'update_time' => $tm];

                       }
                       if( $pay_score>0) {
                           $asset_log[] = ['member_id' => $member_id, 'type' => 2, 'amount' => $pay_score ,
                               'source_type' => 2, 'description' => "到店支付", "change_type" => 1, 'log_type_id' => 62,
                               'relation_id' =>  $shopPay['sp_id'], 'create_time' => $tm, 'update_time' => $tm];

                       }
                       if( $pay_coin>0){
                           $asset_log[] = ['member_id' => $member_id, 'type' => 2, 'amount' => $pay_coin,
                               'source_type' => 2, 'description' => "到店支付", "change_type" => 2, 'log_type_id' => 63,
                               'relation_id' =>  $shopPay['sp_id'], 'create_time' => $tm, 'update_time' => $tm];
                       }
                       $num=Db::name("member_asset_log")->insertAll($asset_log);
                       if($num<=0){
                           throw new Exception("更新失败10");
                       }
                       if($pay_score>0||$pay_coin>0){
                           $sql="update mm_member_asset set frozen_score=frozen_score-$pay_score,pay_frozen_score=pay_frozen_score-$pay_score,frozen_coin=frozen_coin-$pay_coin where member_id=".$member_id." and score>=$pay_score and frozen_score>=$pay_coin and pay_frozen_score>=$pay_score ";
                           $num=Db::query($sql);
                           if($num<=0){
                               throw new Exception("更新失败");
                           }
                           $num=Db::name("member_asset_log")->where(['member_id'=>$member_id,'relation_id'=>$shopPay['sp_id'],"log_type_id"=>['in',[53,54]]])->delete();
                           if($num<=0){
                               throw new Exception("更新失败");
                           }
                       }

                        //返利
                       if($pay_coin>0&&$pay_score>0){
                           $shareScore=$pay_score+$pay_wx;
                           $shareCoin=$pay_coin;
                       }elseif($pay_score>0){
                           $shareScore=$pay_score+$pay_wx;
                           $shareCoin=0;

                       }elseif($pay_coin>0){
                           $shareScore=0;
                           $shareCoin=$pay_coin+$pay_wx;
                       }else{
                           $shareScore=$pay_score+$pay_wx;
                           $shareCoin=0;
                       }

                        $store_share_score=sprintf("%.2f",$shareScore*(100-$rebate_rate)/100);
                        $store_share_coin=sprintf("%.2f",$shareCoin*(100-$rebate_rate)/100);
                        $mem_share_score=sprintf("%.2f",$shareScore*$rebate_rate/100);;
                        $mem_share_coin=sprintf("%.2f",$shareCoin*$rebate_rate/100);
                        //商家
                       if( $store_share_score>0){
                           $asset_log=[];
                           $asset_log[] = ['member_id' => $store_member_id, 'type' => 1, 'amount' => $store_share_score ,
                               'source_type' => 2, 'description' => "用户到店消费", "change_type" => 1, 'log_type_id' => 64,
                               'relation_id' =>  $shopPay['sp_id'], 'create_time' => $tm, 'update_time' => $tm];
                       }
                       if( $store_share_coin>0){
                           if( $pay_coin>0){
                               $asset_log[] = ['member_id' => $store_member_id, 'type' => 1, 'amount' => $store_share_coin,
                                   'source_type' => 2, 'description' => "用户到店消费", "change_type" => 2, 'log_type_id' => 65,
                                   'relation_id' =>  $shopPay['sp_id'], 'create_time' => $tm, 'update_time' => $tm];
                           }
                       }
                       $num=Db::name("member_asset_log")->insertAll($asset_log);
                       if($num<=0){
                           throw new Exception("更新失败10");
                       }
                       $sql="update mm_member_asset set score=score+$store_share_score,coin=coin+$store_share_coin  where member_id=".$store_member_id;
                       $num=Db::query($sql);
                       if($num<=0){
                           throw new Exception("更新失败");
                       }
                        //客户
                       $asset_log=[];
                       if( $mem_share_score>0) {
                           $asset_log[] = ['member_id' => $member_id, 'type' => 1, 'amount' => $mem_share_score ,
                               'source_type' => 2, 'description' => "到店支付返利", "change_type" => 1, 'log_type_id' => 66,
                               'relation_id' =>  $shopPay['sp_id'], 'create_time' => $tm, 'update_time' => $tm];

                       }
                       if( $mem_share_coin>0){
                           $asset_log[] = ['member_id' => $member_id, 'type' => 1, 'amount' => $mem_share_coin,
                               'source_type' => 2, 'description' => "到店支付返利", "change_type" => 2, 'log_type_id' => 67,
                               'relation_id' =>  $shopPay['sp_id'], 'create_time' => $tm, 'update_time' => $tm];
                       }
                       $num=Db::name("member_asset_log")->insertAll($asset_log);
                       if($num<=0){
                           throw new Exception("更新失败10");
                       }
                       $sql="update mm_member_asset set score=score+ $mem_share_score,coin=coin+$mem_share_coin where member_id=".$member_id;
                       $num=Db::query($sql);
                       if($num<=0){
                           throw new Exception("更新失败");
                       }
                        //更改订单状态
                       $payData=[];
                       $payData["give_status"]="1";
                       $payData["status"]=1;
                       $payData['update_time']=$tm;
                       $nums=Db::name("shop_pay")->where(['consume_sn'=>$out_trade_no])->update($payData);
                       if($nums<=0){
                           throw  new Exception("操作失败");
                       }
                       Db::commit();
                       echo 'SUCCESS';
                   }catch (Exception $e){
                       Db::rollback();
                       echo 'FAIL';
                   }
               }else{
                   //金额不对
                   echo 'FAIL';


               }

            }else{
                echo 'FAIL';
            }
        }else{
            echo 'FAIL';
        }
    }

    /**
     * 会员升级支付
     */

    public function gradePayment(){
        $xml = file_get_contents('php://input'); //接受通知参数；
        $res_xml=json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($res_xml, true);
        /*$result['out_trade_no']='202007221515442091';
        $result['trade_type']='';
        $result['total_fee']=1;
        $result['return_code']='SUCCESS';
        $result['result_code']='SUCCESS';*/

        if($result) {
            //如果成功返回了
            $out_trade_no = $result['out_trade_no'];
            $trade_type = $result['trade_type'];  //判断是否是jsapi支付
            $real_money = $result['total_fee'] / 100;
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {

                $tm=time();
                //获取直接支付信息
                $gradePay=Db::name("member_grade_order")->where(['order_sn'=>$out_trade_no])->find();

                if($real_money==$gradePay['wx_money']&& !in_array($gradePay['status'],[1,3])){

                    Db::startTrans();
                    try{
                        $member_id=$gradePay['member_id'];
                        $amount= $gradePay['amount'];
                        $pay_score= $gradePay['score_money'];
                        $pay_coin= $gradePay['coin_money'];
                        $pay_wx= $gradePay['wx_money'];
                        $asset_log=[];
                        if($gradePay['grade_type']==3){
                            $cnt="升级金卡";
                            //消息内容会员等级
                            $m_str="金卡";

                        }
                        if($gradePay['grade_type']==4){
                            $cnt="升级钻卡";
                            //消息内容会员等级
                            $m_str="钻卡";
                        }

                        if($pay_wx>0){//生成微信支付订单记录
                            $asset_log[] = ['member_id' => $member_id, 'type' => 2, 'amount' =>$pay_wx ,
                                'source_type' => 2, 'description' => $cnt, "change_type" => 3, 'log_type_id' => 35,
                                'relation_id' => $gradePay['gradeID'], 'create_time' => $tm, 'update_time' => $tm];
                        }

                        if( $pay_score>0) {
                            $asset_log[] = ['member_id' => $member_id, 'type' => 2, 'amount' => $pay_score ,
                                'source_type' => 2, 'description' => $cnt, "change_type" => 1, 'log_type_id' => 12,
                                'relation_id' =>   $gradePay['gradeID'], 'create_time' => $tm, 'update_time' => $tm];
                        }
                        if( $pay_coin>0){
                            $asset_log[] = ['member_id' => $member_id, 'type' => 2, 'amount' => $pay_coin,
                                'source_type' => 2, 'description' => $cnt, "change_type" => 2, 'log_type_id' =>34,
                                'relation_id' =>   $gradePay['gradeID'], 'create_time' => $tm, 'update_time' => $tm];
                        }
                        if($pay_score>0||$pay_coin>0){

                            $num=Db::name("member_asset_log")
                                ->where(['member_id'=>$member_id,'relation_id'=> $gradePay['gradeID'],
                                    "log_type_id"=>['in',[53,54]]])->delete();
                            if($num<=0){
                                throw new Exception("更新失败");
//                                dump(999);
                            }
                        }

                        //升级奖励
                        if(($pay_score+$pay_wx)==$amount&&$pay_coin==0){//全现金支付
                            if($gradePay['grade_type']==3){
                                $reward=Db::name("system_config")->where(['field_name'=>'grade_golden_card'])
                                    ->value("field_value");
                            }elseif($gradePay['grade_type']==4){
                                $reward=Db::name("system_config")->where(['field_name'=>'grade_drill_card'])
                                    ->value("field_value");
                            }else{
                                throw new Exception("更新失败");
//                                dump(888);
                            }
                            $pay_coin+=$reward;
                            $asset_log[] = ['member_id' => $member_id, 'type' => 1, 'amount' => $pay_coin,
                                'source_type' => 2, 'description' => $cnt, "change_type" => 2, 'log_type_id' =>71,
                                'relation_id' =>   $gradePay['gradeID'], 'create_time' => $tm, 'update_time' => $tm];

                            //会员升级奖励----发送消息  升级金卡，钻卡有奖励
                            $msgs['create_time']=time();
                            $msgs['member_id']=$member_id;
                            $msgs['title']='奖励到帐通知';
                            $msgs['content']="您已升级为".$m_str."会员，您获得会员升级奖".$reward."金币，请及时查看！";
                            $msgs['object_type']=2;
                            $msgs['object_arr']=$member_id;
                            $msgs['class_type']=14;
                            Db::name('message')->insert($msgs);

                        }

                        if($pay_score>0||$pay_coin>0){
                            $sql="update mm_member_asset set frozen_score=frozen_score-$pay_score,
    pay_frozen_score=pay_frozen_score-$pay_score,frozen_coin=frozen_coin-$pay_coin where member_id=".$member_id." and 
    score>=$pay_score and frozen_score>=$pay_coin and pay_frozen_score>=$pay_score ";
                            $num=Db::query($sql);
                            if($num<=0){
                                throw new Exception("更新失败");
//                                dump(777);
                            }
                        }
                        $num=Db::name("member_asset_log")->insertAll($asset_log);
                        if($num<=0){
                            throw new Exception("更新失败10");
//                            dump(666);
                        }

                        $num=Db::name("member_grade")
                            ->insert(['member_id'=>$member_id,'grade_type'=>$gradePay['grade_type'],
                                'start_time'=>$gradePay['start_time'],'end_time'=>$gradePay['end_time']]);
                        if($num<=0){
                            throw new Exception("更新失败10");
//                            dump(555);
                        }

                        //分销
                        $asset_log2=[];
                        $memberInfo=Db::name("member")->where(['member_id'=>$member_id])
                            ->field("uid_1,uid_2")->find();

                        $uid_1=$memberInfo['uid_1'];//直推
                        $uid_2=$memberInfo['uid_2'];//间推
                        if($uid_1>0){
                            $uid_level1=Db::name("member_grade")
                                ->where(['member_id'=>$uid_1,'start_time'=>['elt', $tm],'end_time'=>['egt', $tm]])
                                ->order("grade_type desc,grade_id desc ")->value("grade_type");
                            if($uid_level1<=2){//直推为普通或银卡会员
                                $grade_points_award=Db::name("system_config")
                                    ->where(['field_name'=>'grade_points_award1'])->value("field_value");
                            }else{
                                $grade_points_award=Db::name("system_config")
                                    ->where(['field_name'=>'grade_points_award2'])->value("field_value");
                            }

                        }else{ //无推荐人
                            $grade_points_award=Db::name("system_config")->where(['field_name'=>'grade_points_award1'])->value("field_value");
                        }

                        $grade_points_award=json_decode($grade_points_award,true);

                        $proportion=array_sum($grade_points_award);

                        $direct_push=$grade_points_award['direct_push']/$proportion;
                        if($uid_1<=0){
                            $direct_push=0;
                            $inter_push=0;
                        }else{
                            if($uid_2>0){
                                $inter_push=$grade_points_award['inter_push']/$proportion;
                            }else{
                                $inter_push=0;
                            }
                        }

                        //子公司
                        //$city_company=$grade_points_award['city_company']/$proportion;
                        //平台
                        //$platform=1-$direct_push-$inter_push-$city_company;
                        if( $direct_push>0){//直推
                            $disAmount=$amount*$direct_push;

                            $asset_log2[] = ['member_id' => $uid_1, 'type' => 1, 'amount' =>  $disAmount,
                                'source_type' => 2, 'description' => "会员升级推荐奖", "change_type" =>1, 'log_type_id' => 1,
                                'relation_id' => $gradePay['gradeID'], 'create_time' => $tm, 'update_time' => $tm,'release_status'=>2];
                            $num=Db::name("member_asset")->where(['member_id'=>$uid_1])
                                ->setInc("frozen_score",$disAmount);
                            if($num<=0){
                                throw new Exception("更新失败");
                            }

                            //判断会员与上级的会员等级
                            $uid_level=Db::name("member_grade")
                                ->where(['member_id'=>$uid_1,'start_time'=>['elt', $tm],'end_time'=>['egt', $tm]])
                                ->order("grade_type desc,grade_id desc ")->value("grade_type");
                            if($uid_level<$gradePay['grade_type']){
                                if($uid_level==4){
                                    $uid1_str='钻卡';
                                }elseif($uid_level==3){
                                    $uid1_str='金卡';
                                }elseif($uid_level==2){
                                    $uid1_str='银卡';
                                }else{
                                    $uid1_str='普卡';
                                }

                                $msg['content']="您邀请推荐的会员".$memberInfo['nickName']."，已成为".$m_str."会员，
                            您当前等级为".$uid1_str."会员，无法获得会员升级推荐佣金".$direct_push."%:".$disAmount."积分，
                            请升级为同级或者大于该会员等级后，即可获得该奖励";
                                $msg['msg_type']=3;

                            }else{
                                $msg['content']="您邀请推荐的会员".$memberInfo['nickName']."，已成为".$m_str."会员，
                            您已获得会员升级推荐佣金".$direct_push."%:".$disAmount."积分，请及时查看！";
                            }

                            //会员升级直推奖励----发送消息
                            $msg['create_time']=time();
                            $msg['member_id']=$member_id;
                            $msg['title']='奖励到帐通知';
                            $msg['object_type']=2;
                            $msg['object_arr']=$uid_1;
                            $msg['class_type']=14;
                            Db::name('message')->insert($msg);

                        }
                        if( $inter_push>0){//间推
                            $disAmount=$amount*$inter_push;
                            $asset_log2[] = ['member_id' => $uid_2, 'type' => 1, 'amount' =>  $disAmount,
                                'source_type' => 2, 'description' => "会员升级推荐奖", "change_type" =>1, 'log_type_id' => 1,
                                'relation_id' => $gradePay['gradeID'], 'create_time' => $tm, 'update_time' => $tm,'release_status'=>2];
                            $num=Db::name("member_asset")->where(['member_id'=>$uid_2])
                                ->setInc("frozen_score",$disAmount);
                            if($num<=0){
                                throw new Exception("更新失败");
//                                dump(333);
                            }

                            //会员升级间推奖励----发送消息
                            $msg2['create_time']=time();
                            $msg2['member_id']=$member_id;
                            $msg2['title']='奖励到帐通知';
                            $msg2['content']="您邀请推荐的会员".$memberInfo['nickName']."，已成为".$m_str."会员，
                            您已获得会员升级推荐佣金".$inter_push.":".$disAmount."积分，请及时查看！";
                            $msg2['object_type']=2;
                            $msg2['object_arr']=$uid_2;
                            $msg2['class_type']=14;
                            Db::name('message')->insert($msg2);

                        }

                        $num=Db::name("member_asset_log")->insertAll($asset_log2);
                        if($num<=0){
                            throw new Exception("更新失败10");
                            //dump(111);
                        }

                        //更改订单状态
                        $payData=[];
                        $payData["give_status"]="1";
                        $payData["status"]=1;
                        $payData['update_time']=$tm;
                        $nums=Db::name("member_grade_order")->where(['order_sn'=>$out_trade_no])->update($payData);
                        if($nums<=0){
                            throw  new Exception("操作失败");
                            //dump(222);
                        }

                        Db::commit();
                        echo 'SUCCESS';
                    }catch (Exception $e){
                        Db::rollback();
                        echo 'FAIL4';
                    }
                }else{
                    //金额不对
                    echo 'FAIL3';


                }

            }else{
                echo 'FAIL2';
            }
        }else{
            echo 'FAIL';
        }
    }


}